/*!
 * Purdy - an HTML helper add-on for gNius b20100804163990401
 * http://phiveleven.com/gnius
 *
 * Copyright (c) 2009 Phive Eleven
 * Dual licensed under the MIT and GPL licenses.
 * http://phiveleven.com/gnius/License
 *
 */
(function($, gNius){

  var Purdy = {
    /**
     * Replace all timestamps inside <time> tags with relative,
     * human-readable time (X seconds/minutes ago, etc.)
     */
    timestamp: function(container){
      container.find('time').each(function(i, node){
        $(node).html(function(i, html){
          return html.replace(/\d{10}/, function(timestamp){
            return _wrap.time(timestamp);
          });
        });
      });
    },

    /**
     * Replace <media> tags (not HTML5) with video or image tags.
     */
    media: function(container){
      container.find('media').each(function(i, node){
        node = $(node);
        var type = node.attr('type');
        if (type in _wrap) {
          node.replaceWith(_wrap[type]({
            src: node.html(),
            className: node.attr('class'),
            alt: node.attr('alt')
          }));
        }
      });
    },

    /**
     * Truncate content based on the length of each truncate attribute.
     * A "More..." link can be added at the end if it already exists and
     * must have a class=more.
     * This simple truncate doesn't deal with embedded tags, just html.
     */
    truncate: function(container){
      container.find('truncate').each(function(i, node){
        node = $(node);
        var more = node.find('a.more').remove();
        var max_chars = node.attr('truncate');
        var re_trunc = new RegExp('.{'+max_chars+'}?\\b');
        node.html(function(i, html){
          // truncate before first break
          html = html.replace(/^(.+?)\s*<br\/?>.+/m, '$1...');
          // truncate for length
          var match = html.match(re_truncate);
          if (!match) return html;
          return match[0] + '...';
        }).append(more);
      });
    }
  };

  /*
   * HTML wrappers
   */
  var _wrap = {
    /**
     * @param since {number}
     * @param to {number} (optional)
     */
    time: function(since, to){
      to = to || +new Date / 1000;
      var diff = to - since/1000;

      if (diff < 60) return diff + ' seconds ago';
      if ((diff/=60) < 60) return diff|0 + ' minutes ago';
      if ((diff/=24) < 24) return diff|0 + ' hours ago';
      if ((diff/=7) < 7) return diff|0 + ' days ago';
      if ((diff/=4) < 4) return diff|0 + ' weeks ago';

      var date = new Date(since);
      var month = ['January', 'February', 'March',
                   'April', 'May', 'June', 'July',
                   'August', 'September', 'October',
                   'November', 'December'][date.getMonth()];
      var YEAR = 365*24*60*60;
      var year = (to - since < YEAR) ? '' : ' ' + date.getFullYear();
      return month + ' ' + (date.getDate()) + year;
    },

    /**
     * @param config {object}
     */
    img: function(config){
      if (!config.src) return '';
      config.src = config.src.replace(/www\.youtube\.com\/v\/([^\/]+)/,
                                      'img.youtube.com/vi/$1/0.jpg');
      if (!config.src.match(/\.(jpe?g)|(gif)|(png)$/)) return '';
      config.alt = config.alt || config.src;
      return $('<img>', config).outerHTML();
    },

    /**
     * @param config {object}
     */
    video: function(config){
      var defaults = {
        width: 400,
        height: 325
      };
      $.extend(defaults, config);
      var videoUrl = obj.url+'&hl=en&fs=1&color1=0x006699&color2=0x54abd6';
      return $('<object>', config)
        .append($('<param>', {
          name: 'movie',
          value: videoUrl
        })).append($('<param>', {
          name: 'allowFullScreen',
          value: 'true'
        })).append($('<param>', {
          name: 'allowscriptaccess',
          value: 'always'
        })).append($('<embed>', {
          height: config.height,
          width: config.width,
          allowfullscreen: 'true',
          allowscriptaccess: 'always',
          type: 'application/x-shockwave-flash',
          src: videoUrl
        })).outerHTML();
    },

    /**
     * @param config {object}
     */
    link: function(config){
      config.html = config.html +
        config.href.match(/(?:^http:\/\/)(?:www\/)?([^\/]+)/)[1];
      return $('<a />', config).outerHTML();
    }
  };


  $.fn.extend({
    outerHTML : function() {
      return $('<div>').append( this[0].clone() ).html();
    }
  });

  gNius.Purdy = Purdy;
})(jQuery, gNius);